<?php
require_once("config/app_webview_config.php");
$prime_map = array(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257);
//购物车类型映射
$cart_type = [
    //user_shopping里的type => pay_user_discount里的sales_type
    '0' => 1,
    '1' => 2,
    '2' => 3,
    '3' => 4,
    'singleItem' => 1,
    'tz' => 2,
    'GJJPackage' => 3,
    'diy' => 1
];

class Item
{
    public $id;
    public $price_base;
    public $name;
    public $price_discount;
    public $fields;
    public $previewTable;
    private $priceTable;
    private $mat_list;
    private $fab_list;
    private $size_list;
    private $prime_i;

    function __construct($id)
    {
        $this->prime_i = 0;
        $this->id = intval($id);
        $this->fields = array();
        $this->initBase();
        $this->initMainFields();
        $this->initExtFields();
        $this->initPreviewTable();
    }

    private function initBase()
    {
        global $conn;
        $query = "SELECT * FROM sys_item WHERE id=" . $this->id;
        $result = mysqli_query($conn, $query);
        $row = mysqli_fetch_array($result);
        $this->price_base = $row["price_base"];
        $this->price_discount = $row["price_discount"] == 0 ? 1 : $row["price_discount"];
        $this->name = $row["name"] ? $row["name"] : '';
        $this->fab_list = $row["fabric_list"] != '0' && $row["fabric_list"] != NULL ? explode(",", $row["fabric_list"]) : array();
        $this->mat_list = $row["material_list"] != '0' && $row["material_list"] != NULL ? explode(",", $row["material_list"]) : array();
    }

    private function initMainFields()
    {
        global $conn;
        global $url;
        global $path;
        global $prime_map;
        //初始化面料
        if (count($this->fab_list) > 0) {
            $this->fields["fab"] = array(
                "name" => "面料",
                "objs" => array()
            );
            $i = 0;
            $str = "(base_sys_fabric.id=" . implode(" OR base_sys_fabric.id=", $this->fab_list) . ")";
            $query = "SELECT base_sys_fabric.id,TRIM(base_sys_fabric.`name`) AS `name`,sys_image.url FROM base_sys_fabric,sys_image WHERE " . $str . " AND sys_image.id=base_sys_fabric.img_thumb_id";
            $result = mysqli_query($conn, $query);
            while ($row = mysqli_fetch_array($result)) {
                $this->fields["fab"]["objs"][$i] = array(
                    "id" => $row["id"],
                    "text" => $row["name"],
                    "url" => $url . $path . $row["url"],//取中图
                    "prime" => $prime_map[$this->prime_i]
                );
                $i++;
                $this->prime_i++;
            }
        }
        //初始化材质
        if (count($this->mat_list) > 0) {
            $this->fields["mat"] = array(
                "name" => "材质",
                "objs" => array()
            );
            $i = 0;
            $str = "(base_sys_material.id=" . implode(" OR base_sys_material.id=", $this->mat_list) . ")";
            $query = "SELECT base_sys_material.id,TRIM(base_sys_material.`name`) AS `name`,sys_image.url FROM base_sys_material,sys_image WHERE " . $str . " AND sys_image.id=base_sys_material.img_thumb_id";
            $result = mysqli_query($conn, $query);
            while ($row = mysqli_fetch_array($result)) {
                $this->fields["mat"]["objs"][$i] = array(
                    "id" => $row["id"],
                    "text" => $row["name"],
                    "url" => $url . $path . $row["url"],//取中图
                    "prime" => $prime_map[$this->prime_i]
                );
                $i++;
                $this->prime_i++;
            }
        }
        //初始化规格
        $i = 0;
        $query = "SELECT * FROM sys_item_size WHERE sys_item_size.item_id=" . $this->id;
        $result = mysqli_query($conn, $query);
        while ($row = mysqli_fetch_array($result)) {
            if ($i == 0) {
                $this->fields["size"] = array(
                    "name" => "规格",
                    "objs" => array()
                );
            }
            $this->fields["size"]["objs"][$i] = array(
                "id" => $row["id"],
                "text" => trim($row["size"]),
                "prime" => $prime_map[$this->prime_i]
            );
            $i++;
            $this->prime_i++;
        }
    }

    private function initExtFields()
    {
        global $conn;
        global $prime_map;
        $query = "SELECT DISTINCT grp_price_ex.id,TRIM(grp_price_ex.`name`) AS `name` FROM grp_price_ex,sys_item_prices,sys_item_prices_ex WHERE sys_item_prices.item_id = " . $this->id . " AND sys_item_prices.id = sys_item_prices_ex.price_id AND sys_item_prices_ex.price_ex_id = grp_price_ex.id";
        $result = mysqli_query($conn, $query);
        while ($row = mysqli_fetch_array($result)) {
            $this->fields["ext_" . $row['id']] = array(
                "name" => $row['name'],
                "objs" => array()
            );
            $query1 = "SELECT DISTINCT TRIM(sys_item_prices_ex.price_ex_value) AS price_ex_value FROM `sys_item_prices_ex`,sys_item_prices WHERE sys_item_prices.id=sys_item_prices_ex.price_id AND sys_item_prices.item_id=" . $this->id . " AND sys_item_prices_ex.price_ex_id=" . $row["id"];
            $result1 = mysqli_query($conn, $query1);
            $i = 0;
            while ($row1 = mysqli_fetch_array($result1)) {
                $this->fields["ext_" . $row['id']]["objs"][$i] = array(
                    "id" => $row1["price_ex_value"],
                    "text" => $row1["price_ex_value"],
                    "prime" => $prime_map[$this->prime_i]
                );
                $i++;
                $this->prime_i++;
            }
        }
    }

    private function initPreviewTable()
    {
        global $conn;
        global $url;
        global $path;
        $this->previewTable = array();
        $query = "SELECT base_sys_preview.fid,base_sys_preview.mid,small.url AS small_url,thumb.url AS thumb_url,large.url AS large_url FROM `base_sys_preview`,sys_image small,sys_image thumb,sys_image large WHERE base_sys_preview.item_id = " . $this->id . " AND base_sys_preview.img_small_id=small.id AND base_sys_preview.img_thumb_id=thumb.id AND base_sys_preview.img_url_id=large.id";
        $result = mysqli_query($conn, $query);
        $i = 0;
        while ($row = mysqli_fetch_array($result)) {
            $this->previewTable[$i] = array();
            $t = 1;
            if (array_key_exists("fab", $this->fields)) {
                foreach ($this->fields["fab"]["objs"] as $value) {
                    if ($row["fid"] == $value["id"]) {
                        $t = $t * $value["prime"];
                        break;
                    }
                }
            }
            if (array_key_exists("mat", $this->fields)) {
                foreach ($this->fields["mat"]["objs"] as $value) {
                    if ($row["mid"] == $value["id"]) {
                        $t = $t * $value["prime"];
                        break;
                    }
                }
            }
            $this->previewTable[$i] = array(
                "prime" => $t,
                "url" => $url . $path . $row["small_url"]
            );
            $i++;
        }
    }

    function getPriceTable()
    {
        $this->priceTable = array();
        global $conn;
        global $prime_map;
        $query = "SELECT MIN(id) FROM sys_item_prices WHERE item_id = " . $this->id;
        $result = mysqli_query($conn, $query);
        $row = mysqli_fetch_array($result);
        $min_id = $row[0];

        $query = "SELECT * FROM sys_item_prices WHERE item_id = " . $this->id;
        $result = mysqli_query($conn, $query);
        while ($row = mysqli_fetch_array($result)) {
            $this->priceTable[$row['id'] - $min_id]["prime"] = 1;
            $this->priceTable[$row['id'] - $min_id]["price_id"] = $row["id"];
            if (array_key_exists("fab", $this->fields)) {
                $this->priceTable[$row['id'] - $min_id]["fab"] = $row["fabric_id"];
                foreach ($this->fields["fab"]["objs"] as $v) {
                    if ($v["id"] == $row["fabric_id"]) {
                        $this->priceTable[$row['id'] - $min_id]["prime"] = $this->priceTable[$row['id'] - $min_id]["prime"] * $v["prime"];
                        break;
                    }
                }
            }
            if (array_key_exists("mat", $this->fields)) {
                $this->priceTable[$row['id'] - $min_id]["mat"] = $row["material_id"];
                foreach ($this->fields["mat"]["objs"] as $v) {
                    if ($v["id"] == $row["material_id"]) {
                        $this->priceTable[$row['id'] - $min_id]["prime"] = $this->priceTable[$row['id'] - $min_id]["prime"] * $v["prime"];
                        break;
                    }
                }
            }
            if (array_key_exists("size", $this->fields)) {
                $this->priceTable[$row['id'] - $min_id]["size"] = $row["size_id"];
                foreach ($this->fields["size"]["objs"] as $v) {
                    if ($v["id"] == $row["size_id"]) {
                        $this->priceTable[$row['id'] - $min_id]["prime"] = $this->priceTable[$row['id'] - $min_id]["prime"] * $v["prime"];
                        break;
                    }
                }
            }
            $this->priceTable[$row['id'] - $min_id]["price_discount"] = ($row["price_discount"] == 0 ? 1 : $row["price_discount"]);
            $this->priceTable[$row['id'] - $min_id]["price_custom"] = $row["price_custom"];
        }
        $query = "SELECT sys_item_prices.id AS price_id,sys_item_prices.item_id,sys_item_prices.size_id,sys_item_prices.fabric_id,sys_item_prices.material_id,sys_item_prices.price_custom,sys_item_prices.price_discount,sys_item_prices_ex.price_ex_id,TRIM(sys_item_prices_ex.price_ex_value) AS price_ex_value FROM sys_item_prices RIGHT JOIN sys_item_prices_ex ON (sys_item_prices_ex.price_id = sys_item_prices.id) WHERE item_id =" . $this->id;
        $result = mysqli_query($conn, $query);
        while ($row = mysqli_fetch_array($result)) {
            $this->priceTable[$row['price_id'] - $min_id]["ext_" . $row["price_ex_id"]] = $row["price_ex_value"];
            foreach ($this->fields["ext_" . $row["price_ex_id"]]["objs"] as $v) {
                if ($v["id"] == $row["price_ex_value"]) {
                    $this->priceTable[$row['price_id'] - $min_id]["prime"] = $this->priceTable[$row['price_id'] - $min_id]["prime"] * $v["prime"];
                    break;
                }
            }
        }
        if (count($this->priceTable) == 0) {
            $t = 1;
            for ($i = $this->prime_i - 1; $i >= 0; $i--) {
                $t = $t * $prime_map[$i];
            }
            $this->priceTable[0] = array(
                "prime" => $t,
                "price_discount" => 1,
                "price_custom" => 0
            );
        }
        return $this->priceTable;
    }
}

function getTzDiyCount($item_arr, $type, $id)
{
    global $conn;
    if ($type == 1) {//套装
        for ($i = count($item_arr) - 1; $i >= 0; $i--) {
            $sql = 'SELECT pay_state,count,item_id,pos FROM taozhuang_pos WHERE tzid=' . $id . ' AND id=' . $item_arr[$i]['id'];
            //echo $sql."\n";
            $res = mysqli_query($conn, $sql);
            $row = mysqli_fetch_array($res);
            if ($row['pay_state'] == 0) {
                array_splice($item_arr, $i, 1);
                continue;
            }
            $row['pay_state'] == 2 ? $item_arr[$i]['exclude'] = true : $item_arr[$i]['exclude'] = false;
            $item_arr[$i]['count'] = intval($row['count']);
            $item_arr[$i]['item_id'] = intval($row['item_id']);
            $item_arr[$i]['pos'] = intval($row['pos']);
        }
    } elseif ($type == 2) {//DIY
        // for($i=count($item_arr)-1;$i>=0;$i--) {

        // }
    }
    return $item_arr;
}

//获得price id
/**
 * @param $crowd_price_id
 * @return array $ret 0 priceid 1 sku_id
 */
function getPriceIdOrSku($crowd_price_id)
{
    global $conn;
    $ret = [];
    $sql = "SELECT 
                crowd_price.size AS size_id,
                base_sys_preview.fid AS fab_id,
                base_sys_preview.mid AS mat_id,
                base_sys_preview.item_id
            FROM `crowd_price`
            LEFT JOIN base_sys_preview ON base_sys_preview.id=crowd_price.preview_id
            WHERE crowd_price.id=" . $crowd_price_id;
    $res = mysqli_query($conn, $sql);
    $row = mysqli_fetch_array($res);

    $sku_id = [];

    $sql2 = "SELECT id
            FROM sys_item_prices
            WHERE item_id=" . $row["item_id"];
    if (!empty($row["size_id"])) {
        $sku_id['size'] = $row["size_id"];
        $sql2 .= " AND size_id=" . $row["size_id"];
    }
    if (!empty($row["fab_id"])) {
        $sku_id['fab'] = $row["fab_id"];
        $sql2 .= " AND fabric_id=" . $row["fab_id"];
    }
    if (!empty($row["mat_id"])) {
        $sku_id['mat'] = $row["mat_id"];
        $sql2 .= " AND material_id=" . $row["mat_id"];
    }
    $res2 = mysqli_query($conn, $sql2);
    $row2 = mysqli_fetch_array($res2);

    if (!empty($row2["id"])) {
        $ret["price_id"] = $row2["id"];
    } else {
        $ret["sku_id"] = $sku_id;
    }
    return $ret;
}

//获取crowd_price 表数据
function getCrowd($crowd_price_id)
{
    global $conn;

    $sql = "SELECT 
              *
            FROM crowd_price
            LEFT JOIN crowd_item ON crowd_item.id=crowd_price.crowd_id
            WHERE crowd_price.id=" . $crowd_price_id;
    $res = mysqli_query($conn, $sql);
    $row = mysqli_fetch_array($res);
    return $row;
}

//完善单品信息
function parseItem($item_array, $with_img = false)//:[{"item_id":,"price_id":,"count":,"sku_id":{"fab":1,}},]至少四个默认值
{
    global $conn;
    foreach ($item_array as $key => $value) {
        if (isset($value['price_id']) && $value['price_id']) {
            $value["sku"] = array();
            $value["sku_id"] = array();
            $sql = "SELECT sys_item.`name`,
					sys_item.price_base,
					sys_item.price_discount,
					sys_item_prices.price_custom AS custom_price_custom,
					sys_item.supply_cycle,
					sys_item.app_return,
					sys_item.brand_id,
					sys_item.class_id,
					sys_item_prices.price_discount AS custom_price_discount,
					base_sys_fabric.id AS fabId,
					TRIM(base_sys_fabric.`name`) AS fabValue,
					base_sys_material.id AS matId,
					TRIM(base_sys_material.`name`) AS matValue,
					sys_item_size.id AS sizeId,
					TRIM(sys_item_size.size) AS sizeValue,
					sys_image.url 
					FROM sys_item_prices 
					LEFT JOIN base_sys_fabric ON sys_item_prices.fabric_id=base_sys_fabric.id 
					LEFT JOIN base_sys_material ON sys_item_prices.material_id=base_sys_material.id 
					LEFT JOIN sys_item_size ON sys_item_prices.size_id=sys_item_size.id 
					LEFT JOIN sys_item ON sys_item.id=sys_item_prices.item_id 
					LEFT JOIN sys_image ON sys_item.img_small_id=sys_image.id 
					WHERE sys_item_prices.id=" . $value["price_id"];
            $res = mysqli_query($conn, $sql);
            $row = mysqli_fetch_array($res);
            $value["name"] = $row["name"];
            $value['app_return'] = $row['app_return'];
            $value["price_base"] = $row["price_base"];
            $value['class_id'] = $row['class_id'];
            $value["brand_id"] = $row["brand_id"];
            $value["price_discount"] = ($row["price_discount"] <= 0 ? 1 : $row["price_discount"]);
            $value["_price_custom"] = $row["custom_price_custom"];
            $value["_price_discount"] = $row["custom_price_discount"] <= 0 ? 1 : $row["custom_price_discount"];
            $value["lead_time"] = strlen($row["supply_cycle"]) > 5 ? $row["supply_cycle"] : null;
            if ($row["fabValue"] != NULL) {
                $value["sku"]["fab"] = trim($row["fabValue"]);
                $value["sku_id"]["fab"] = $row["fabId"];
            }
            if ($row["matValue"] != NULL) {
                $value["sku"]["mat"] = trim($row["matValue"]);
                $value["sku_id"]["mat"] = $row["matId"];
            }
            if ($row["sizeValue"] != NULL) {
                $value["sku"]["size"] = trim($row["sizeValue"]);
                $value["sku_id"]["size"] = $row["sizeId"];
            }

            ($row["url"] != NULL && $with_img) ? $value["img_url"] = $row["url"] : "";
            $price_ex_res = mysqli_query($conn, "SELECT sys_item_prices_ex.price_ex_id,sys_item_prices_ex.price_ex_value,grp_price_ex.`name` FROM sys_item_prices_ex LEFT JOIN grp_price_ex ON sys_item_prices_ex.price_ex_id=grp_price_ex.id WHERE sys_item_prices_ex.price_id=" . $value["price_id"]);
            while ($row = mysqli_fetch_array($price_ex_res)) {
                $value["sku"][$row["name"]] = trim($row["price_ex_value"]);
                $value["sku_id"]["ext_" . $row["price_ex_id"]] = $row["price_ex_value"];
            }
        } else {
            $sql = "SELECT 
			        sys_item.`name`,
			        sys_item.price_base,
			        sys_item.price_discount,
			        sys_item.app_return,
			        sys_item.class_id,
			        sys_item.brand_id,";
            if (isset($value['sku_id']['fab'])) {
                $sql = $sql . "base_sys_fabric.id AS fabId,";
                $sql = $sql . "base_sys_fabric.`name` AS fabValue,";
            }
            if (isset($value['sku_id']['mat'])) {
                $sql = $sql . "base_sys_material.id AS matId,";
                $sql = $sql . "base_sys_material.`name` AS matValue,";
            }
            if (isset($value['sku_id']['size'])) {
                $sql = $sql . "sys_item_size.id AS sizeId,";
                $sql = $sql . "sys_item_size.size AS sizeValue,";
            }
            $sql = $sql . "sys_image.url,sys_item.supply_cycle FROM `sys_item` ";

            if (isset($value['sku_id']['mat'])) {
                $sql = $sql . "LEFT JOIN base_sys_material ON base_sys_material.id=" . $value['sku_id']['mat'] . " ";
            }
            if (isset($value['sku_id']['fab'])) {
                $sql = $sql . "LEFT JOIN base_sys_fabric ON base_sys_fabric.id=" . $value['sku_id']['fab'] . " ";
            }
            if (isset($value['sku_id']['size'])) {
                $sql = $sql . "LEFT JOIN sys_item_size ON sys_item_size.id=" . $value['sku_id']['size'] . " ";
            }
            $sql = $sql . "LEFT JOIN sys_image ON sys_item.img_small_id=sys_image.id WHERE sys_item.id=" . $value["item_id"];
            $res = mysqli_query($conn, $sql);
            $row = mysqli_fetch_array($res);
            $value["name"] = trim($row["name"]);
            if (isset($row["fabValue"]) && $row["fabValue"] != NULL) {
                $value["sku"]["fab"] = trim($row["fabValue"]);
                $value["sku_id"]["fab"] = $row["fabId"];
            }
            if (isset($row["matValue"]) && $row["matValue"] != NULL) {
                $value["sku"]["mat"] = trim($row["matValue"]);
                $value["sku_id"]["mat"] = $row["matId"];
            }
            if (isset($row["sizeId"]) && $row["sizeId"] != NULL) {
                $value["sku"]["size"] = trim($row["sizeValue"]);
                $value["sku_id"]["size"] = $row["sizeId"];
            }
            ($row["url"] != NULL && $with_img) ? $value["img_url"] = $row["url"] : "";
            $value["price_base"] = $row["price_base"];
            $value['app_return'] = $row['app_return'];
            $value['class_id'] = $row['class_id'];
            $value["brand_id"] = $row["brand_id"];
            $value["price_discount"] = ($row["price_discount"] <= 0 ? 1 : $row["price_discount"]);
            $value["_price_custom"] = 0;//定制的
            $value["_price_discount"] = 1;//默认的折扣
            $value["lead_time"] = strlen($row["supply_cycle"]) > 5 ? $row["supply_cycle"] : null;
        }
        $item_array[$key] = $value;
    }
    return $item_array;
}

function getTz($tzid)
{
    global $conn;
    $sql = "SELECT * FROM taozhuang WHERE sid = " . $tzid;
    $res = mysqli_query($conn, $sql);
    $row = mysqli_fetch_array($res);
    return $row;
}

//拼接SKU数组成字符串
function parseSku($skuArray)
{
    $str1 = "";
    $str2 = "";
    foreach ($skuArray as $key => $value) {
        switch ($key) {
            case 'fab':
                $str1 = $str1 . "面料" . ":&nbsp;" . $value . ";&nbsp;";
                break;
            case 'mat':
                $str1 = $str1 . "材质" . ":&nbsp;" . $value . ";&nbsp;";
                break;
            case 'size':
                $str2 = $str2 . "规格" . ":&nbsp;" . $value . ";&nbsp;";
                break;
            default:
                $str2 = $str2 . $key . ":&nbsp;" . $value . ";&nbsp;";
                break;
        }
    }
    return $str1 . "<br>" . $str2;
}

//获得用户类型
function getUserType($user_id)
{
    global $conn;
    $user_res = mysqli_query($conn, "SELECT user_type,user_type_class FROM user_info WHERE id=" . $user_id);
    $row = mysqli_fetch_array($user_res);
    return [
        "user_type" => $row["user_type"],
        "user_type_class" => $row['user_type_class']
    ];
}

//获得地址表全部地址
function getAddress($user_id)
{
    global $conn;
    $address = array();
    $i = 0;
    $address_res = mysqli_query($conn, "SELECT * FROM `user_address` WHERE uid=" . $user_id);
    while ($row = mysqli_fetch_array($address_res)) {
        $address[$i++] = array(
            "id" => $row["id"],
            "city" => $row["area"],
            "detail" => $row["address"],
            "postCode" => $row["postcode"],
            "name" => $row["name"],
            "mobile" => $row["mobile"],
            "tel" => $row["tel"],
            "default" => $row["type"]
        );
    }
    return $address;
}

//获得购物车所有记录
function getShoppingCartAll($user_id)
{
    global $conn;
    $arr = array();
    $i = 0;
    $result = mysqli_query($conn, "SELECT * FROM `user_shopping` WHERE user_id = " . $user_id . " ORDER BY id DESC");
    if (isset($result) && (!empty($result))) {
        while ($row = mysqli_fetch_array($result)) {
            $jsondata = json_decode($row['jsondata'], true);
            $jsondata["items"] = parseItem($jsondata["items"], true);
            $jsondata["info"]["cart_id"] = $row["id"];
            $jsondata["info"]["cart_time"] = date("Y-m-d", $row['createtime']);
            $jsondata["info"]["cart_type"] = $row["type"];
            //如果为套装
            if ($jsondata["info"]["cart_type"] == 1) {
                $sql = "SELECT taozhuang.`name`,taozhuang.price_custom,sys_image.url FROM taozhuang LEFT JOIN sys_image ON taozhuang.img_small_id=sys_image.id WHERE taozhuang.sid=" . $jsondata["info"]['id'];
                $res = mysqli_query($conn, $sql);
                $row = mysqli_fetch_array($res);
                $jsondata["info"]['name'] = $row['name'];
                $jsondata["info"]['discount'] = $row['price_custom'];
                $jsondata["info"]['img_url'] = $row['url'];
            } //如果为diy
            elseif ($jsondata["info"]["cart_type"] == 4) {
                $sql = "SELECT diy.`name`,sys_image.url FROM diy LEFT JOIN sys_image ON diy.img_small_id=sys_image.id WHERE diy.id=" . $jsondata["info"]['id'];
                $res = mysqli_query($conn, $sql);
                $row = mysqli_fetch_array($res);
                $jsondata["info"]['name'] = $row['name'];
                $jsondata["info"]['img_url'] = $row['url'];
            }
            $arr[$i++] = $jsondata;
        }
    }
    return $arr;
}

//删除购物车一组记录
function deleteShoppingCart($cart_id_array)
{
    global $conn;
    $str = implode(',', $cart_id_array);
    $res = mysqli_query($conn, "DELETE FROM user_shopping WHERE id IN(" . $str . ")");
    if ($res) {
        return true;
    } else {
        return false;
    }
}

//标记优惠券已使用
function useCoupon($user_coupon_arr)
{
    global $conn;
    if (!empty($user_coupon_arr)) {
        $str = implode(',', $user_coupon_arr);
        $res = mysqli_query($conn, 'UPDATE user_coupon SET state = 1, useing_time = UNIX_TIMESTAMP() WHERE id IN(' . $str . ') AND state = 0;');
        return $res;
    }
}

//根据地址表id取得地址字符串
function getAddressStr($address_id)
{
    global $conn;
    $sql = "SELECT * FROM user_address WHERE id=" . $address_id;
    $res = mysqli_query($conn, $sql);
    $row = mysqli_fetch_array($res);
    $address = str_replace(";", "", $row["area"] . " " . $row["address"]) . ";" . $row["name"] . ";" . $row["mobile"] . ";" . $row["tel"] . ";" . $row["postcode"];
    return $address;
}

defined('SALES_TYPE_ITEM');
defined('SALES_TYPE_TZ');
defined('SALES_TYPE_PACKAGE');
defined('SALES_TYPE_WZPACKAGE');
define('SALES_TYPE_ITEM', 1);
define('SALES_TYPE_TZ', 2);
define('SALES_TYPE_PACKAGE', 3);
define('SALES_TYPE_WZPACKAGE', 4);
//获取用户折扣Obj
function getUserDiscount($user_type, $user_type_class)
{
    global $conn;
    $user_discount = array();
    $default_service = 0;
    $service_count = 1;
    $i = 0;
    $sql = "SELECT * FROM pay_user_discount WHERE user_type=" . $user_type . " AND user_type_class=" . $user_type_class;
    $res = mysqli_query($conn, $sql);
    while ($row = mysqli_fetch_array($res)) {
        if (!isset($user_discount[$row['sales_type']])) {
            $user_discount[$row['sales_type']] = array();
        }
        $user_discount[$row['sales_type']] = [
            'discount' => $row['discount_rate'],
            'service' => $row['post_sales_service']
        ];
    }
    return $user_discount;
}

//根据用户user_type user_type_class 查询用户是否有折扣
  function getIfHasDiscount($user_type,$user_type_class){
    global $conn;
   $sql="select id from pay_user_discount where user_type=$user_type and  user_type_class=$user_type_class";
   $res=mysqli_query($conn, $sql);
   $list=mysqli_fetch_array($res);
   if(count($list)>0){
        return true;
    }else{
        return false;
    }
}  
function getCommonVipDiscount()
{
    global $conn;
    $sql = "SELECT * FROM pay_user_discount WHERE user_type=3 AND user_type_class=1 AND sales_type=1 AND post_sales_service=1";
    $res = mysqli_query($conn, $sql);
    $row = mysqli_fetch_array($res);
    return $row['discount_rate'];
}

function uploadImg()
{
    $dir = "../gjj/backend/web/" . $_POST['dir'];
    mkdir($dir, 0777, true);
    if (move_uploaded_file($_FILES["img"]["tmp_name"], $dir . $_POST["name"] . "." . $_POST["file_type"])) {
        echo "done";
    } else {
        echo "error";
    }
}

//加购物车表
function submitShopingCart($user_id, $type, $order_arr)//$order={"item_id":1,"price_id":2,"count":3,"sku_id":{"fab":1}}
{
    global $conn;
    $count = $order_arr["info"]["count"];
    $jsondata = json_encode($order_arr, JSON_UNESCAPED_UNICODE);
    $sql = "insert into user_shopping (user_id,type,jsondata,count,createtime) value ('$user_id','$type','$jsondata','$count',unix_timestamp())";
    if (mysqli_query($conn, $sql)) {
        $res = mysqli_query($conn, "select last_insert_id()");
        $row = mysqli_fetch_array($res);
        echo $row[0];
    } else {
        echo 0;
    }
}

function coupon_calc($item_price, $item_count, $coupon_obj)
{
    $price = 0;
    switch ($coupon_obj['coupon_rule']) {
        //满就减
        case 'M':
            if ($item_price * $item_count >= intval($coupon_obj['coupon_price'])) {
                $price = $item_price * $item_count - intval($coupon_obj['price']);
            } else {
                $price = $item_price * $item_count;
            }
            break;
        //直减
        case 'S':
            $price = $item_price * $item_count - intval($coupon_obj['price']);
            break;
        //折扣率
        case 'D':
            $price = $item_price * $item_count * floatval($coupon_obj['price']);
            break;
        //每满减
        case 'N':
            $price = $item_price * $item_count - intval(($item_price * $item_count) / intval($coupon_obj['coupon_price'])) * intval($coupon_obj['price']);
            break;
    }
    return $price;
}

//提交众筹订单
function submitCrowd($user_id, $address_id, $message, $item_info, $crowd_price_id, $post_total_price)
{
    global $conn;


    //生成订单号
    $sql = "SELECT * FROM user_info WHERE id=" . $user_id;
    $res = mysqli_query($conn, $sql);
    $row = mysqli_fetch_array($res);
    $trade_no = substr($row["username"], -4, 4) . substr($row["id"], -4, 4) . strtotime("now");
    //用户身份类型
    $user_type = $row["user_type"];

    //取得地址
    $address = getAddressStr($address_id);


    //解析item_info
    $item_info2 = [];
    $item_info2['items'] = $item_info;

    $parseInfo = [];
    $parseInfo['singleItem'] = [];
    $parseInfo['singleItem'][0]['items'] = [];
    $parseInfo['singleItem'][0]['items'][0] = parseItem($item_info2, false)['items'];
    $parseInfo['singleItem'][0]['info'] = ["cart_type" => 0, "sales_service" => "0", "user_discount" => "1"];

    //众筹信息
    $crowd = getCrowd($crowd_price_id);
    $postage = $crowd['postage'];
    $crowd_price = $crowd['price'];

    //众筹是否开启
    if ($crowd['useing'] != 1) {
        $ret = array(
            "state" => false,
            "trade_no" => NULL,
            "error" => '该商品未开启众筹活动'
        );
        echo json_encode($ret, JSON_UNESCAPED_UNICODE);
        return;
    }

    //是否超额
    //if ($crowd['exceed_limit'] == 0 && $crowd['amRaised'] < $crowd['tarAmount']) {
    //    $ret = array(
    //        "state" => false,
    //        "trade_no" => NULL,
    //        "error" => '该单品已经超出众筹数量限制'
    //    );
    //    echo json_encode($ret, JSON_UNESCAPED_UNICODE);
    //    return;
    //}

    //众筹数量限制
	if ($crowd['exceed_limit'] == 0) {
		if ($item_info['count'] > ($crowd['price_limit'] - $crowd['buy_count'])) {
			$ret = array(
				"state" => false,
				"trade_no" => NULL,
				"error" => '超出众筹购买限制或数量不正确'
			);
			echo json_encode($ret, JSON_UNESCAPED_UNICODE);
			return;
		}
	}

    //众筹时间限制
    if ($crowd['start_time'] > time() || $crowd['end_time'] < time()) {
        $ret = array(
            "state" => false,
            "trade_no" => NULL,
            "error" => '该单品的众筹活动未开始或已经结束'
        );
        echo json_encode($ret, JSON_UNESCAPED_UNICODE);
        return;
    }

    //用户类型限制
    $user_t = getUserType($user_id);
    $user_type = $user_t['user_type'];
    if (!in_array($user_t['user_type'], explode(',', $crowd['user_types']))) {
        $ret = array(
            "state" => false,
            "trade_no" => NULL,
            "error" => '您不符可参与本众筹商品的用户类型'
        );
        echo json_encode($ret, JSON_UNESCAPED_UNICODE);
        return;
    }

    $parseInfo['singleItem'][0]['items'][0]['final_price'] = $crowd_price;


    //计算价格
    $total_price = intval($item_info['count'] * $crowd_price);
    $post_total_price=intval($post_total_price);
    if ($total_price != $post_total_price) {
        echo '计算出错 ';
        return;
    }

    //写入数据库
    $sql = "INSERT INTO `pay_trade`(
		trade_no,
		user_id,
		address,
		message,
		number,
		price,
		price_modify,
		price_state,
		create_time,
		modify_time,
		trade_state,
		audit_state,
		refund_audit,
		content,
		trade_class,
		crowd_price_id
		) 
		VALUES(
		'" . $trade_no . "',
		" . $user_id . ",
		'" . $address . "',
		'" . $message . "',
		" . $item_info['count'] . ",
		" . $total_price . ",
		" . $total_price . ",
		0,
		unix_timestamp(now()),
		unix_timestamp(now()),
		0,
		0,
		0,
		'" . json_encode($parseInfo, JSON_UNESCAPED_UNICODE) . "',
		2,
		" . $crowd_price_id . "
		)";
    if (mysqli_query($conn, $sql)) {
        $ret = array(
            "state" => true,
            "trade_no" => $trade_no
        );
    } else {
        $ret = array(
            "state" => false,
            "trade_no" => NULL,
            "error" => $sql
        );
    }
    echo json_encode($ret, JSON_UNESCAPED_UNICODE);

    //发短信
    $sql = "SELECT * FROM user_info WHERE id=" . $user_id;
    $res = mysqli_query($conn, $sql);
    $row = mysqli_fetch_array($res);
    if ($row["user_from"] == 1) {
        $tel = $row["tel"];
    } else {
        $sql = "SELECT * FROM user_address WHERE id=" . $address_id;
        $res = mysqli_query($conn, $sql);
        $row = mysqli_fetch_array($res);
        $tel = $row["mobile"];
    }
    $msg = '我们已经收到您的订单，感谢信任，您可以随时回JAJAHOME App查看订单详情。客服电话：400-690-3766';
    send_mobile_SMS($tel, $msg);
}

//提交订单到订单表  lwx 8/9新增 $installprice,$designprice
function submitOrder($user_id, $address_id, $message, $item_info, $design_serve, $coupon, $post_total_price, $sales_logistics, $sales_design,$installprice,$designprice,$expenseprice,$item_memo)
{

    //test
    $item_memo=explode(",", $item_memo);
    if(isset($item_info["singleItem"])){
        foreach ($item_info['singleItem'] as $i => &$value) {
            $value['items'][0]["item_memo"]=$item_memo[$i];
        }
    }

    unset($i); unset($value);
    $tz_memo_i=0;
   if(key_exists("singleItem",$item_info)){
    $tz_memo_i=count($item_info["singleItem"]);
}

    if (isset($item_info['tz'])) {
        foreach ($item_info['tz'] as $i => &$value) {
            for($k=0;$k<count($value["items"]);$k++){
                $value["items"][$k]["item_memo"]=$item_memo[$tz_memo_i];
                $tz_memo_i++;
            }
        }
    }
    unset($i); unset($value);
    //test
    $design_discount = 0.03;
    global $conn, $cart_type;
    $cart_id_array = array();
    $cart_id_index = 0;
    $consolt = 0;//是否待改价
    $expenseprice=floor($expenseprice);
    //取得优惠券
    $coupon_arr = [];
    $item_id_arr = [];
    $item_count = [];
    $tz_id_arr = [];
    $tz_count = [];
    
    if (isset($item_info['singleItem'])) {
        foreach ($item_info['singleItem'] as $i => $value) {
            //找出所有单品id
            $item_id_arr[] = $value['items'][0]['item_id'];
            //找出所有单品数量
            if (!isset($item_count[$value['items'][0]['item_id']])) {
                $item_count[$value['items'][0]['item_id']] = 0;
            }
            $item_count[$value['items'][0]['item_id']] = $item_count[$value['items'][0]['item_id']] + $value['items'][0]['count'];
        }
        $coupon_arr['item'] = getItemCoupon($item_id_arr, $user_id, $item_count);
        $coupon_arr['class'] = getClassCoupon($item_id_arr, $user_id, $item_count);
        $coupon_arr['brand'] = getBrandCoupon($item_id_arr, $user_id, $item_count);
        $coupon_arr['all'] = getAllCoupon($user_id);
    }
    if (isset($item_info['tz'])) {
        foreach ($item_info['tz'] as $i => $value) {
            $tz_id_arr[] = $value['info']['id'];
            if (!isset($tz_count[$value['info']['id']])) {
                $tz_count[$value['info']['id']] = 0;
            }
            $tz_count[$value['info']['id']] = $tz_count[$value['info']['id']] + $value['info']['count'];
        }
        $coupon_arr['set'] = getTzCoupon($tz_id_arr, $user_id, $tz_count);
        $coupon_arr['all'] = getAllCoupon($user_id);
    }
   
     
 
    
    //筛选优惠券，优惠券都只有一张
    if (isset($coupon_arr['item']) && !empty($coupon_arr['item'])) {
        foreach ($coupon_arr['item'] as $id => $value) {
            if (in_array($id, $coupon)) {
                $coupon_arr['item'] = $coupon_arr['item'][$id];
                break;
            } else {
                unset($coupon_arr['item'][$id]);
            }
        }
    }
    if (isset($coupon_arr['class']) && !empty($coupon_arr['class'])) {
        foreach ($coupon_arr['class'] as $id => $value) {
            if (in_array($id, $coupon)) {
                $coupon_arr['class'] = $coupon_arr['class'][$id];
                break;
            } else {
                unset($coupon_arr['class'][$id]);
            }
        }
    }
    if (isset($coupon_arr['brand']) && !empty($coupon_arr['brand'])) {
        foreach ($coupon_arr['brand'] as $id => $value) {
            if (in_array($id, $coupon)) {
                $coupon_arr['brand'] = $coupon_arr['brand'][$id];
                break;
            } else {
                unset($coupon_arr['brand'][$id]);
            }
        }
    }
    if (isset($coupon_arr['set']) && !empty($coupon_arr['set'])) {
        foreach ($coupon_arr['set'] as $id => $value) {
            if (in_array($id, $coupon)) {
                $coupon_arr['set'] = $coupon_arr['set'][$id];
                break;
            } else {
                unset($coupon_arr['set'][$id]);
            }
        }
    }
    if (isset($coupon_arr['all']) && !empty($coupon_arr['all'])) {
        foreach ($coupon_arr['all'] as $id => $value) {
            if (in_array($id, $coupon)) {
                $coupon_arr['all'] = $coupon_arr['all'][$id];
                break;
            } else {
                unset($coupon_arr['all'][$id]);
            }
        }
    }

    //生成订单号
    $sql = "SELECT * FROM user_info WHERE id=" . $user_id;
    $res = mysqli_query($conn, $sql);
    $row = mysqli_fetch_array($res);
    $trade_no = substr($row["username"], -4, 4) . substr($row["id"], -4, 4) . strtotime("now");
    //用户身份类型
    $user_type = $row["user_type"];
    $user_type_class = $row['user_type_class'];
    //用户折扣
    $user_discount = getUserDiscount($user_type, $user_type_class);
    //取得地址
    $address = getAddressStr($address_id);

    //计算价格
    $total_price = 0;
    $total_count = 0;

    //解析item_info
    foreach ($item_info as $key => $obj) {
        foreach ($obj as $content_index => $content) {
            //判断服务类型
           /*  if (isset($cart_type[$content['info']['cart_type']]) && isset($user_discount[$cart_type[$content['info']['cart_type']]]['service'])) {
                $item_info[$key][$content_index]["info"]["sales_service"] = $user_discount[$cart_type[$content['info']['cart_type']]]['service'];
            } else {
                $item_info[$key][$content_index]["info"]["sales_service"] = 0;
            } */
            $item_info[$key][$content_index]["info"]["sales_service"] =$design_serve;
            //解析item详细信息
            $item_info[$key][$content_index]["items"] = parseItem($content["items"]);
            if (isset($content["info"]["cart_id"])) {
                $cart_id_array[$cart_id_index++] = $content["info"]["cart_id"];
                unset($item_info[$key][$content_index]["info"]["cart_id"]);
            }
            //如果存在用户折扣,折扣写进info里
            if (isset($user_discount[$cart_type[$content['info']['cart_type']]]['service'])) {
                $item_info[$key][$content_index]["info"]["user_discount"] = $user_discount[$cart_type[$content['info']['cart_type']]]['discount'];
            }
            //写入优惠券信息
            if ($key == 'singleItem') {
                if (!empty($coupon_arr['item']) && $content['items'][0]['item_id'] == $coupon_arr['item']['action_id']) {
                    $item_info[$key][$content_index]['info']['user_coupon_id'] = $coupon_arr['item']['id'];
                } elseif (!empty($coupon_arr['brand']) && $content['items'][0]['brand_id'] == $coupon_arr['brand']['action_id']) {
                    $item_info[$key][$content_index]['info']['user_coupon_id'] = $coupon_arr['brand']['id'];
                } elseif (!empty($coupon_arr['class']) && $content['items'][0]['class_id'] == $coupon_arr['class']['action_id']) {
                    $item_info[$key][$content_index]['info']['user_coupon_id'] = $coupon_arr['class']['id'];
                }
            } elseif ($key == 'tz' && !empty($coupon_arr['set']) && $content['info']['id'] == $coupon_arr['set']['action_id']) {
                $item_info[$key][$content_index]['info']['user_coupon_id'] = $coupon_arr['set']['id'];
            } elseif (!empty($coupon_arr['all'])) {
                $item_info[$key][$content_index]['info']['user_coupon_id'] = $coupon_arr['all']['id'];
            }
        }
    }

    //计算价格
    $use_item_coupon = false;

    $item_total_price = 0;
    $item_total_count = 0;

    $tz_total_price = 0;
    $tz_total_count = 0;

    $total_class_price = 0;
    $total_brand_price = 0;
    $total_all_price = 0;

    $total_old_price=0;//lwx新增  计算订单单品原价
    $total_price = 0;
    $total_count = 0;

    foreach ($item_info as $key => $obj) {
        if ($key == 'singleItem') {
            foreach ($obj as $content_index => $content) {
                $item = $content['items'][0];
                //如果是赠品，跳过计算
                if (isset($content["info"]["exclude"]) && !empty($content["info"]["exclude"]) && in_array($item['item_id'], $content["info"]["exclude"])) {
                    $item_info[$key][$content_index]["items"][0]["final_price"] = 0;
                    continue;
                } //如果存在单品优惠券
                elseif (!empty($coupon_arr['item']) && isset($coupon_arr['item']['action_id']) && ($coupon_arr['item']['action_id'] == $item['item_id'] || $coupon_arr['item']['action_id'] == 0) && !$use_item_coupon) {
                    $item_info[$key][$content_index]["items"][0]["final_price"] = $item['price_base'] + $item['_price_custom'];
                    $item_total_price = $item_total_price + coupon_calc($item_info[$key][$content_index]["items"][0]["final_price"], $item['count'], $coupon_arr['item']);
                    $use_item_coupon = true;
                } //如果存在类目优惠券
                elseif (!empty($coupon_arr['class']) && $item['class_id'] == $coupon_arr['class']['action_id']) {
                    $item_info[$key][$content_index]["items"][0]["final_price"] = $item['price_base'] + $item['_price_custom'];
                    $total_class_price = $total_class_price + $item_info[$key][$content_index]["items"][0]["final_price"] * $item['count'];

                } //如果存在品牌优惠券
                elseif (!empty($coupon_arr['brand']) && $item['brand_id'] == $coupon_arr['brand']['action_id']) {
                    $item_info[$key][$content_index]["items"][0]["final_price"] = $item['price_base'] + $item['_price_custom'];
                    $total_brand_price = $total_brand_price + $item_info[$key][$content_index]["items"][0]["final_price"] * $item['count'];

                } //如果存在全场优惠券
                elseif (!empty($coupon_arr['all'])) {
                    $item_info[$key][$content_index]["items"][0]["final_price"] = $item['price_base'] + $item['_price_custom'];
                    $total_all_price = $total_all_price + $item_info[$key][$content_index]["items"][0]["final_price"] * $item['count'];
                } //如果存在用户折扣
                elseif (isset($user_discount[$cart_type[$content['info']['cart_type']]]['discount'])) {
                    $item_info[$key][$content_index]["items"][0]["final_price"] = (intval($item["price_base"]) ? round(($item["price_base"] + $item["_price_custom"]) * ($user_discount[$cart_type[$content['info']['cart_type']]]['discount']), 2) : 0);
                    $item_total_price = $item_total_price + $item_info[$key][$content_index]["items"][0]["final_price"] * $item["count"];
                } //否则计算单品本身折扣
                else {
                    $item_info[$key][$content_index]["items"][0]["final_price"] = (intval($item["price_base"]) ? round($item["price_base"] * $item["price_discount"] + $item["_price_custom"] * $item["_price_discount"], 2) : 0);
                    $item_total_price = $item_total_price + $item_info[$key][$content_index]["items"][0]["final_price"] * $item["count"];
                }
                $total_count = $total_count + $item['count'];
                //lwx添加
                $total_old_price=$total_old_price+ $item['count']*($item['price_base']+$item['_price_custom']);
                
            }

            $total_price = $total_price + $item_total_price;
            if ($use_item_coupon && !empty($coupon_arr['item'])) {
                if (!isset($item_info['coupon'])) {
                    $item_info['coupon'] = [];
                }
                $item_info['coupon']['item'] = $coupon_arr['item'];
            }
            //单品类目优惠
            if ($total_class_price && !empty($coupon_arr['class'])) {
                $total_price = $total_price + coupon_calc($total_class_price, 1, $coupon_arr['class']);
                if (!isset($item_info['coupon'])) {
                    $item_info['coupon'] = [];
                }
                $item_info['coupon']['item'] = $coupon_arr['class'];
            }
            //单品品牌优惠
            if ($total_brand_price && !empty($coupon_arr['brand'])) {
                $total_price = $total_price + coupon_calc($total_brand_price, 1, $coupon_arr['brand']);
                if (!isset($item_info['coupon'])) {
                    $item_info['coupon'] = [];
                }
                $item_info['coupon']['item'] = $coupon_arr['brand'];
            }
        } elseif ($key == 'tz') {

            $max_tz_price = 0;
            $max_tz_index = 0;

            $max_action_tz_price = 0;
            $max_action_tz_index = 0;
            $temp_old_price=0;
            foreach ($obj as $content_index => $content) {
                $item_info[$key][$content_index]['info']['origin_price'] = 0;
                $item_info[$key][$content_index]['info']['final_price'] = 0;
                //先累加单品
                $t_count = 0;

                foreach ($content['items'] as $i => $item) {
                    //如果是赠品，跳过计算
                    $item_exclude = false;
                    if (isset($content["info"]["exclude"]) && !empty($content["info"]["exclude"]) && in_array($item['item_id'], $content["info"]["exclude"])) {
                        $item_info[$key][$content_index]["items"][$i]["final_price"] = 0;
                        $item_exclude = true;
                    } //如果有用户折扣
                    elseif (isset($user_discount[$cart_type[$content['info']['cart_type']]]['discount'])) {
                        $item_info[$key][$content_index]["items"][$i]["final_price"] = (intval($item["price_base"]) ? round(($item["price_base"] + $item["_price_custom"]) * ($user_discount[$cart_type[$content['info']['cart_type']]]['discount']), 2) : 0);
                        $item_info[$key][$content_index]['info']['final_price'] = $item_info[$key][$content_index]['info']['final_price'] + $item_info[$key][$content_index]["items"][$i]["final_price"] * $item["count"] * $item_info[$key][$content_index]['info']['count'];
                    } //否则计算套装折扣
                    //elseif (isset($content["info"]["discount"])) {
						
					elseif (($content["info"]["discount"])>0 && ($content["info"]["discount"])<1) {	
                        $discount = floatval($content["info"]["discount"]) == 0 ? 1 : floatval($content["info"]["discount"]);
						/*  修正注册用户计算套装中的单品折扣
                        $item_info[$key][$content_index]["items"][$i]["final_price"] = (intval($item["price_base"]) ? round(($item["price_base"] + $item["_price_custom"]) * ($discount), 2) : 0);
						*/
						$item_info[$key][$content_index]["items"][$i]["final_price"] = (intval($item["price_base"]) ? round((($item["price_base"] * $item["price_discount"] + $item["_price_custom"] * $item["_price_discount"])*($content["info"]["discount"])), 2) : 0);
					
                        $item_info[$key][$content_index]['info']['final_price'] = $item_info[$key][$content_index]['info']['final_price'] + $item_info[$key][$content_index]["items"][$i]["final_price"] * $item["count"] * $item_info[$key][$content_index]['info']['count'];    
                    } else {
                        $item_info[$key][$content_index]["items"][$i]["final_price"] = (intval($item["price_base"]) ? round(($item["price_base"] * $item["price_discount"] + $item["_price_custom"] * $item["_price_discount"]), 2) : 0);
                        $item_info[$key][$content_index]['info']['final_price'] = $item_info[$key][$content_index]['info']['final_price'] + $item_info[$key][$content_index]["items"][$i]["final_price"] * $item["count"] * $item_info[$key][$content_index]['info']['count'];
                    }
                    //计算全场优惠券用到的原价总和
                    if (!$item_exclude && !empty($coupon_arr['all'])) {
                        $item_info[$key][$content_index]["items"][$i]["final_price"] = intval($item["price_base"]) ? round($item["price_base"] + $item["_price_custom"]) : 0;
                        $total_all_price = $total_all_price + $item_info[$key][$content_index]["items"][$i]["final_price"] * $item["count"] * $item_info[$key][$content_index]['info']['count'];
                    }

                    $t_count = $t_count + $item['count'] * $item_info[$key][$content_index]['info']['count'];

                    if (!(isset($content["info"]["exclude"]) && !empty($content["info"]["exclude"]) && in_array($item['item_id'], $content["info"]["exclude"]))) {
                        $item_info[$key][$content_index]['info']['origin_price'] = $item_info[$key][$content_index]['info']['origin_price'] + round(($item["price_base"] + $item["_price_custom"]) * $item["count"], 2);
                       
                    }
                   /*  计算原价算法，有点不对，暂时用origin_price代替
                    *  if(isset($content["info"]["exclude"])){
                        if( !in_array($item['item_id'], $content["info"]["exclude"])){
                            $temp_old_price=$temp_old_price+ round(($item["price_base"] + $item["_price_custom"]) * $item["count"]*$item_info[$key][$content_index]['info']['count'], 2);
                        }
                    }else{
                           $temp_old_price=$temp_old_price+ round(($item["price_base"] + $item["_price_custom"]) * $item["count"]*$item_info[$key][$content_index]['info']['count'], 2);
                    } */
                }
               
                //lwx 新增
                $total_old_price=$total_old_price+$item_info[$key][$content_index]['info']['origin_price']*$item_info[$key][$content_index]['info']['count'];
                $total_count = $total_count + $t_count;

                $tz_total_price = $tz_total_price + $item_info[$key][$content_index]['info']['final_price'];
                //筛选出最大价格的套装
                if ($item_info[$key][$content_index]['info']['final_price'] > $max_tz_price) {
                    $max_tz_price = $item_info[$key][$content_index]['info']['final_price'];
                    $max_tz_index = $content_index;
                }
                //筛选出最大价格的指定id的套装
                if (!empty($coupon_arr['set']) && $coupon_arr['set']['action_id'] == $content['info']['id']) {
                    if ($item_info[$key][$content_index]['info']['final_price'] > $max_action_tz_price) {
                        $max_action_tz_price = $item_info[$key][$content_index]['info']['final_price'];
                        $max_action_tz_index = $content_index;
                    }
                }
            }

            //最大价格的指定id的套装计算
            if (!empty($coupon_arr['set']) && $coupon_arr['set']['action_id'] == $item_info[$key][$max_action_tz_index]['info']['id']) {

                $tz_total_price = $tz_total_price - $item_info[$key][$max_action_tz_index]['info']['final_price'];
                $item_info[$key][$max_action_tz_index]['info']['final_price'] = coupon_calc($item_info[$key][$max_action_tz_index]['info']['origin_price'], $item_info[$key][$max_action_tz_index]['info']['count'], $coupon_arr['set']);
               // $tz_total_price = $tz_total_price + $item_info[$key][$content_index]['info']['final_price'];
                $tz_total_price = $tz_total_price + $item_info[$key][$max_tz_index]['info']['final_price'];
                if (!isset($item_info['coupon'])) {
                    $item_info['coupon'] = [];
                }
                $item_info['coupon']['set'] = $coupon_arr['set'];
            }

            //最大价格的套装计算
            if (!empty($coupon_arr['set']) && $coupon_arr['set']['action_id'] == 0) {
                $tz_total_price = $tz_total_price - $item_info[$key][$max_tz_index]['info']['final_price'];
                $item_info[$key][$max_tz_index]['info']['final_price'] = coupon_calc($item_info[$key][$max_tz_index]['info']['origin_price'], $item_info[$key][$max_tz_index]['info']['count'], $coupon_arr['set']);
                $tz_total_price = $tz_total_price + $item_info[$key][$max_tz_index]['info']['final_price'];
                if (!isset($item_info['coupon'])) {
                    $item_info['coupon'] = [];
                }
                $item_info['coupon']['set'] = $coupon_arr['set'];
            }
            $total_price = $total_price + $tz_total_price;
        }
    }
    if (!empty($coupon_arr['all'])) {
        $total_price = intval(coupon_calc($total_all_price, 1, $coupon_arr['all']));
        $item_info['coupon']['all'] = $coupon_arr['all'];
    } else {
        $total_price = intval($total_price);
    }
    //lwx item_info新增installprice  designprice  
    
    $item_info['totle']=array(array("info"=>array("sales_service"=>floor($expenseprice),"sales_logistics"=>floor($installprice),"sales_design"=>floor($designprice)))); 
    //lwx  根据服务计算价格
   /*  if(intval($design_serve)==0&&$user_type>=3){
        //原价格
        $total_old_price=intval($total_old_price);
        //物流费
        $serviceprice=0;
        if($total_old_price<50000){
            $serviceprice=intval($total_old_price*0.15);
        }else{
            $serviceprice=intval($total_old_price*0.15);
           // $serviceprice=intval($total_old_price*0.12);
        }
           $total_price=$total_price+$serviceprice;
    }  */
    // print_r($_POST);
    // echo $total_price."\n";
    // print_r($item_info);
    // return;
    // echo $total_price."\n";
    // echo $post_total_price."\n";
    // return;
/*     echo '   计算的价格total_price:'.$total_price."原价:".$total_old_price."物流费价格：".$serviceprice."传递的价格".$post_total_price;
    return; */
    
    //lwx 8/9新增 $installprice,$designprice
    $total_price=floor($total_price+$expenseprice+$installprice+$designprice);
   if ($total_price != $post_total_price) {
       echo "物流安装费： ".$installprice." 设计费 ： ".$designprice." 服务费： ".$expenseprice;
       echo '计算出错  计算的价格total_price:'.$total_price."原价:".$total_old_price."物流费价格：".$expenseprice."传递的价格".$post_total_price;
        return;
    }  
    //写入数据库
    $sql = "INSERT INTO `pay_trade`(
		trade_no,
		user_id,
        price_freight,
		address,
		message,
		number,
		price,
		price_modify,
		price_state,
		create_time,
		modify_time,
		trade_state,
		audit_state,
		refund_audit,
		content
		) 
		VALUES(
		'" . $trade_no . "',
		" . $user_id . ",
        ".$expenseprice.",
		'" . $address . "',
		'" . $message . "',
		" . $total_count . ",
		" . $total_price . ",
		" . $total_price . ",
		0,
		unix_timestamp(now()),
		unix_timestamp(now()),
		" . $consolt . ",
		0,
		0,
		'" . json_encode($item_info, JSON_UNESCAPED_UNICODE) . "')";
    if (mysqli_query($conn, $sql)) {
        $t = array(
            "state" => true,
            "trade_no" => $trade_no 
        );
        deleteShoppingCart($cart_id_array);
        if (!empty($item_info['coupon'])) {
            $user_coupon_arr = [];
            foreach ($item_info['coupon'] as $type => $value) {
                $user_coupon_arr[] = $value['id'];
            }
            useCoupon($user_coupon_arr);
        }
    } else {
        $t = array(
            "state" => false,
            "trade_no" => NULL,
            "error" => $sql
        );
    }
    
    echo json_encode($t, JSON_UNESCAPED_UNICODE);
    $sql = "SELECT * FROM user_info WHERE id=" . $user_id;
    $res = mysqli_query($conn, $sql);
    $row = mysqli_fetch_array($res);
    if ($row["user_from"] == 1) {
        $tel = $row["tel"];
    } else {
        $sql = "SELECT * FROM user_address WHERE id=" . $address_id;
        $res = mysqli_query($conn, $sql);
        $row = mysqli_fetch_array($res);
        $tel = $row["mobile"];
    }
    $msg = '我们已经收到您的订单，感谢信任，您可以随时回JAJAHOME App查看订单详情。客服电话：400-690-3766';
    //测试注释 
     send_mobile_SMS($tel, $msg);
}

//提交订单完发短信
function request_post($url, $post_data)
{
    if (empty($url) || empty($post_data)) {
        return false;
    }
    $o = "";
    foreach ($post_data as $k => $v) {
        $o .= "$k=" . urlencode($v) . "&";
    }
    $post_data = substr($o, 0, -1);
    $postUrl = $url;
    $curlPost = $post_data;
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL, $postUrl);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    return $data;
}

/**
function send_mobile_SMS($mobile, $message)
{
    $post_data = array();
    $post_data['account'] = iconv('GB2312', 'GB2312', "guojiajia");
    $post_data['pswd'] = iconv('GB2312', 'GB2312', "Gj888888");
    $post_data['mobile'] = $mobile;
    $post_data['msg'] = mb_convert_encoding($message, 'UTF-8', 'auto');
    $url = 'http://222.73.117.156/msg/HttpBatchSendSM?';
    $result = request_post($url, $post_data);
    return $result;
}
*/


	/**
	 * 发送短信
	 * @param  手机号码 $mobile
	 * @param  短信内容 $message
	 */
	function send_mobile_SMS($mobile,$message,$needstatus = 'true'){
	    $code = mt_rand(100000,999999);
	    $postArr = array (
	        'account'  =>  iconv('GB2312', 'GB2312',"N6350024"),
	        'password' => iconv('GB2312', 'GB2312',"061SwgTLOC9ebc"),
	        'msg' => urlencode($message),
	        'phone' => $mobile,
	        'report' => $needstatus
	    );
		
		$time = date("Ymd H:i:s") ;
		$save_log_filename = dirname(__FILE__)."/log_sms.txt" ;
		file_put_contents($save_log_filename,"$time -- $mobile : $message .\r\n",FILE_APPEND);

	    $result = curlPost($GLOBALS['SMS_CALL_URL'], $postArr);
	    return $result;
	    /*  if(!is_null(json_decode($result))){
	     $output=json_decode($result,true);
	     if(isset($output['code'])  && $output['code']=='0'){
	     echo '发送成功';
	     }else{
	     echo $output['errorMsg'];
	     }
	     }else{
	     echo $result;
	     } */
	}
	
	
	/**
	 * 通过CURL发送HTTP请求
	 * @param string $url  //请求URL
	 * @param array $postFields //请求参数
	 * @return mixed
	 *
	 */
	function curlPost($url,$postFields){
	    $postFields = json_encode($postFields);
	    $ch = curl_init ();
	    curl_setopt( $ch, CURLOPT_URL, $url );
	    curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
	        'Content-Type: application/json; charset=utf-8'   //json版本需要填写  Content-Type: application/json;
	    )
	        );
	    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
	    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
	    curl_setopt( $ch, CURLOPT_POST, 1 );
	    curl_setopt( $ch, CURLOPT_POSTFIELDS, $postFields);
	    curl_setopt( $ch, CURLOPT_TIMEOUT,60);
	    curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0);
	    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0);
	    $ret = curl_exec ( $ch );
	    if (false == $ret) {
	        $result = curl_error(  $ch);
	    } else {
	        $rsp = curl_getinfo( $ch, CURLINFO_HTTP_CODE);
	        if (200 != $rsp) {
	            $result = "请求状态 ". $rsp . " " . curl_error($ch);
	        } else {
	            $result = $ret;
	        }
	    }
	    curl_close ( $ch );
	    return $result;
	}	


/********************以下三个函数为单品、套装、diy添加到购物车或立即购买时显示用********************/
function createItemWrapperBefore()
{
    global $user_id;
    $user_info=getUserType($user_id);
    $user_type = $user_info['user_type'];
    //獲取user_type_class
    $user_type_class=$user_info['user_type_class']; 
    $discount_arr = getUserDiscount($user_type, $user_type_class);
    $user_discount = isset($discount_arr[SALES_TYPE_ITEM]['discount'])?$discount_arr[SALES_TYPE_ITEM]['discount']:1;
    
    echo '<style type="text/css">
		.item-wrapper,
		.tz-info-wrapper	{padding:5px;margin-bottom: 20px;background-color: #FFF;box-shadow: 0 2px 0 #E2E2E2;}
		.tz-title			{font-size:16px;}
		.exclude-div		{background-color:rgba(100,100,255,0.1);padding: 5px 5px;margin-bottom:10px;font-size:15px;font-weight:bold;color:#777;}
		.wrapper-header 	{display:table;}
		.wrapper-header>div {display:table-cell;}
		.preview 			{border:1px solid #EEE;vertical-align:middle;}
		.info 				{padding-left:10px;}
		.options 			{margin-top:10px;}
        .name               {font-size: 16px;}
		.preview 			{width:100px;height:100px;font-size:0;text-align:center;}
		.preview img 		{max-width:100%;max-height:100%;}
		.price 				{font-size:16px;}
        .now_price          {color: #F00;}
        .old_price          {color: #AAA;}
		.selected_opt_tag 	{line-height:30px;}
		.opt 				{display:inline-block;margin:5px 4px;border:1px solid #DDD;line-height:8px;}
		.opt img 			{height:60px;width:60px;line-height:12px;}
		.opt div 			{min-width:41px;height:30px;padding: 0 10px;text-align:center;vertical-align:middle;line-height:30px;}
		.opt.selected 		{border-color:#F00;background-color:#F00;color:#FFF;}
		.opt.selected div 	{color:#FFF;}
		.count 				{border-top:1px dashed #DDD;margin: 10px 0 5px 0;padding-top:10px;}
		.tz-info-wrapper 
		.controls 			{float: right;}
		.tz-count 			{display: table;width: 100%;}
		.tz-count>div,
		.count>div 			{display:table-cell;vertical-align:middle;}
		.controls>div 		{display:table-cell;vertical-align:middle;}
		.input>input 		{width:90px;height:30px;box-sizing:border-box;vertical-align:middle;border:1px solid #DDD;border-radius:0;font-size:18px;text-align:center;padding: 0;-webkit-appearance:none;}
		.input 				{margin:10px 5px;}
		.minus,.plus 		{width: 30px;height: 30px;margin:10px;border: 1px solid #DDD;position:relative;box-sizing:border-box;}
		.c1,.c2 			{background-color:#999;position:absolute;}
		.c1 				{width:20px;height:4px;top:12px;left:4px;}
		.c2 				{width:4px;height:20px;top:4px;left:12px;}
		.count-min 			{padding-left:10px;}
		.forbid 			{opacity:0.3;cursor:not-allowed;}
		.wrapper-warning 	{font-size:15px;color:#F00;background-color:rgba(255,0,0,0.1);border-top:1px solid rgba(255,0,0,0.6);border-bottom:1px solid rgba(255,0,0,0.6);text-align: center;padding: 5px 5px;margin-bottom:10px;}
		</style>';

    echo '<script type="text/javascript">
			var beSelect={};
			var previewTable={};
			var priceTable={};
            var isVip = '.($user_type <= 5 && $user_type >= 3? 'true':'false').';
            var user_discount = parseFloat('.$user_discount.');
		  </script>';
}

//创建单个单品选择表单
//new Item()产生的itemObj，isExclude此单品是否是赠品，selected_arr=['fab'=>1,'mat'=>2]，min最小购买数量
function createItemWrapper($itemObj, $isExclude = false, $selected_arr = [], $min = 1)
{
    $wrapper_id = 'wp_' . mt_rand();
    echo '<div class="item-wrapper' . ($isExclude ? " exclude" : "") . '" id="' . $wrapper_id . '" data-itemid="' . $itemObj->id . '" data-pricebase="' . $itemObj->price_base . '" data-pricediscount="' . $itemObj->price_discount . '">
				' . ($isExclude ? '<div class="exclude-div">赠品</div>' : '') . '
				<div class="wrapper-warning hide">请选择规格</div>
				<div class="wrapper-header">
					<div class="preview"><img src="images/photo_bg.png" class="main_img"></div>
				    <div class="info">
				    	<div class="name">' . $itemObj->name . '</div>
				    	<div class="price">' . ($isExclude ? 0 : (intval($itemObj->price_base) ? $itemObj->price_base : "请询价")) . '</div>
				        <div class="selected_opt_name">
				        	<div class="sel_fab"></div>
				        	<div class="sel_mat"></div>
				        </div>
				    </div>
				</div>';
    foreach ($itemObj->fields as $key => $fields) {
        echo "<div class='fields-wrapper'>";
        echo "<div class='fields-name'>" . $fields['name'] . "</div>";
        echo "<div class='fields-opts' data-name='" . $fields['name'] . "' data-wrapperid='" . $wrapper_id . "' data-key='" . $key . "'>";
        $sel_opt_id = (isset($selected_arr[$key]) ? $selected_arr[$key] : null);
        foreach ($fields['objs'] as $opt) {
            if ($sel_opt_id == $opt['id']) {
                echo '<script type="text/javascript">
											if (typeof(beSelect["' . $wrapper_id . '"])=="undefined") {
												beSelect["' . $wrapper_id . '"]={};
											}
											if(typeof(beSelect["' . $wrapper_id . '"]["' . $key . '"])=="undefined"){
												beSelect["' . $wrapper_id . '"]["' . $key . '"]=' . $opt["prime"] . ';
											};
											beSelect["' . $wrapper_id . '"]["' . $key . '"]=' . $opt["prime"] . ';
										  </script>';
            }
            echo "<div class='opt" . ($sel_opt_id == $opt['id'] ? " selected" : "") . "' data-id='" . $opt['id'] . "' data-name='" . $opt['text'] . "' data-prime='" . $opt['prime'] . "'>";
            if (isset($opt['url']) && $opt['url'] != null) {
                echo "<img src='" . $opt['url'] . "' alt='" . $opt['text'] . "'>";
            } else {
                echo "<div>" . $opt['text'] . "</div>";
            }
            echo "</div>";
        }
        echo "</div>";
        echo "</div>";
    }
    if ($isExclude) {
        echo '<div class="count">
							<div class="count-name">
						    	数量
						    </div>
						    <div class="count-min">
						    	<div class="c">' . $min . '</div>
						    </div>
						</div>';
    } else {
        echo '<div class="count">
							<div class="count-name">
						    	数量
						    </div>
						    <div class="controls">
						    	<div>
						    		<div class="minus">
						    			<div class="c1"></div>
						    		</div>
						    	</div>
						    	
						        <div>
						        	<div class="input"><input class="c" type="number" min="' . $min . '" step="1" value="' . $min . '" readonly>
						        	</div>
						        </div>

						        <div>
						        	<div class="plus">
						        		<div class="c1"></div>
						        		<div class="c2"></div>
						        	</div>
						        </div>
						    </div>
						</div>';
    }
    echo '</div>';
    echo "<script type='text/javascript'>
			previewTable['" . $wrapper_id . "']=JSON.parse('" . json_encode($itemObj->previewTable, JSON_UNESCAPED_UNICODE) . "');
			priceTable['" . $wrapper_id . "']=JSON.parse('" . json_encode($itemObj->getPriceTable(), JSON_UNESCAPED_UNICODE) . "');
		  </script>";
    return $wrapper_id;
}

function createItemWrapperAfter()
{
    echo '<script type="text/javascript">
				bindWrapper();
				bindCounter();
				function bindWrapper()
				{
					var opts=document.querySelectorAll(".opt");
					for(var i=0;i<opts.length;i++){
						opts[i].addEventListener("click",optClick);
					}

					var wrapper=document.querySelectorAll(".item-wrapper");
					for(var i=wrapper.length-1;i>=0;i--){
						updateWrapper(wrapper[i].id);
					}
				}

				function optClick()
				{
					if (this.classList.contains("forbid")) {
						return 0;
					}
					var wrapper_id=this.parentNode.parentNode.parentNode.id;
					var this_row=this.parentNode;
					var t=this_row.querySelector(".opt.selected");
					if (t!=null) {
						t.classList.remove("selected");
					}
					if(t!=this&&!this.classList.add("selected"))
					{
						updateWrapper(wrapper_id);
					}else{
						updateWrapper(wrapper_id);
					}
				}
				
				function updateWrapper(wrapper_id)
				{
					var wrapper = document.querySelector("#"+wrapper_id);
					var price_base = parseInt(wrapper.dataset.pricebase);
					var price_discount = parseFloat(wrapper.dataset.pricediscount);

					wrapper.querySelector(".wrapper-warning").classList.add("hide");

					var rows = wrapper.querySelectorAll(".fields-opts"),opts;
					var i,j,k,n,t_prime,allow,price;
					//未选择的规格作判断
					for (i = rows.length-1; i >= 0; i--) { 
						opts = rows[i].querySelectorAll(".opt:not(.selected)");
						prime = 1;
						for(k=rows.length-1; k>=0; k--)
						{
							if (rows[i]==rows[k]) {
								continue;
							}
							if (rows[k].querySelector(".selected")) {
								prime=prime*parseInt(rows[k].querySelector(".selected").dataset.prime);
							}
						}
						for(j=opts.length-1;j>=0;j--)
						{
							t_prime=prime*parseInt(opts[j].dataset.prime);
							allow=false;
							for(n in priceTable[wrapper_id])
							{
								if (priceTable[wrapper_id][n]["prime"] % t_prime == 0) {
									allow=true;
									break;
								}
							}
							if (allow) {
								opts[j].classList.remove("forbid");
							}
							else{
								opts[j].classList.add("forbid");
							}
						}
					}
					//已选择的规格作价格和主图判断
					var sel_opts=wrapper.querySelectorAll(".opt.selected");
					var fat_text_div=wrapper.querySelector(".sel_fab");
					var mat_text_div=wrapper.querySelector(".sel_mat");
					mat_text_div.textContent="";
					fat_text_div.textContent="";
					prime=1;
					for(i=sel_opts.length-1;i>=0;i--){
						prime=prime*parseInt(sel_opts[i].dataset.prime);
						if (sel_opts[i].parentNode.dataset.key=="mat") {
							mat_text_div.textContent="材质："+sel_opts[i].dataset.name;
						}
						if (sel_opts[i].parentNode.dataset.key=="fab") {
							fat_text_div.textContent="面料："+sel_opts[i].dataset.name;
						}
					}
					for(n in priceTable[wrapper_id])
					{
						if(priceTable[wrapper_id][n]["prime"] % prime == 0){
							wrapper.dataset.priceid = typeof(priceTable[wrapper_id][n]["price_id"])=="undefined"?0:priceTable[wrapper_id][n]["price_id"];

                            var price_custom = parseInt(priceTable[wrapper_id][n]["price_custom"]);
                            var custom_discount = parseFloat(priceTable[wrapper_id][n]["price_discount"]);

                            var old_price = price_base + price_custom;
            				var now_price = 0;
            				if (user_discount > 0 && user_discount < 1){
            					now_price = ((price_base + price_custom) * user_discount).toFixed(2);
            				}else{
            					now_price = ((price_base * price_discount + price_custom * custom_discount)).toFixed(2);
            				}
            
            				if (wrapper.classList.contains("exclude")){
            					now_price = 0;
            				}
            				
            				var vipText = "";
            				if (isVip){
            					vipText = "VIP";
            				}
            
            				var price_div = wrapper.querySelector(".price");
            				//两个折扣都为1则不显示原价
            				if(price_discount==1 && custom_discount==1 && user_discount>=1 && !isVip) {
            					if (parseInt(now_price)) {
            						price_div.innerHTML="<span class=\"now_price\">¥ "+now_price+"</span>";
            					}
            					else {
            						price_div.innerHTML="<span class=\"now_price\">请询价</span>";
            					}
            				}
            				else {
            					if (parseInt(now_price)) {
            						price_div.innerHTML="<span class=\"old_price\"><del>¥ "+old_price+"</del></span>&nbsp;&nbsp;<span class=\"now_price\">"+ vipText +"¥ "+now_price+"</span>";
            					}
            					else {
            						price_div.innerHTML="<span class=\"now_price\">请询价</span>";
            					}
            				}
							break;
						}
					}
					for(n in previewTable[wrapper_id])
					{
						if (previewTable[wrapper_id][n]["prime"] % prime == 0) {
							wrapper.querySelector(".main_img").src=previewTable[wrapper_id][n]["url"];
							break;
						}
					}
				}

				function bindCounter()
				{
					var tag=document.querySelectorAll(".minus,.plus");
					var i,j,k;
					for(i=tag.length-1;i>=0;i--)
					{
						tag[i].addEventListener("click",changeCounter);
					}
				}
				function changeCounter()
				{
					var this_input=this.parentNode.parentNode.querySelector("input.c");
					var operate=this.classList[0];
					if (operate==="minus") {
						if (parseInt(this_input.value)<=parseInt(this_input.min)||parseInt(this_input.value)<=0) {
							return;
						}else{
							this_input.value=parseInt(this_input.value)-1;
						}
					}
					else if(operate==="plus")
					{
						if (parseInt(this_input.value)>9999) {
							return;
						}else{
							this_input.value=parseInt(this_input.value)+1;
						}
					}
				}
		  	</script>';
}

/********************购物车显示处理********************/
//处理单品
function shoppingcartItem($cart_arr)
{
    global $url, $path;
    $sign = 0;
    foreach ($cart_arr as $cart_index => $cart_content) {
        if ($cart_content["info"]["cart_type"] == 0) {
            if ($sign == 0) {
                echo '
                <div class="item-container container" data-cart_type="0">
                    <div class="header-info">
                        <div class="header-check">
                            <div class="svg-border item-check-all" data-checked="true"><img class="svg-checkbox" src="images/check-icon.png"><input type="checkbox" checked></div>
                        </div>
                        <div class="header-tag">全选</div>
                        <div class="header-title">单品</div>
                        <div class="d"><div class="dd"></div></div>
                        <div class="edit edit-count">编辑数量</div>
                        <div class="d"><div class="dd"></div></div>
                        <div class="edit edit-delete">删除单品</div>
                    </div>
                ';
            }
            foreach ($cart_content["items"] as $item_index => $value) {
                intval($value["price_base"]) ? $value_price = $value["price_base"] + $value["_price_custom"] : $value_price = "请询价";
                echo '
                    <div class="item-div" data-cartid="' . $cart_content["info"]["cart_id"] . '" data-itemid="' . $value["item_id"] . '" data-priceid="' . $value["price_id"] . '">
                        <div class="item-check">
                            <div class="svg-border item-check-i" data-checked="true"><img class="svg-checkbox" src="images/check-icon.png"><input type="checkbox" checked></div>
                        </div>
                        <div class="item-image">
                            <a href="webView://item_info?id=' . $value['item_id'] . '"><img src="' . $url . $path . $value["img_url"] . '"></a>
                        </div>
                        <div class="item-info">
                            <div class="item-title"><a href="webView://item_info?id=' . $value['item_id'] . '">' . $value["name"] . '</a></div>
                            <div class="item-number">
                                <div class="item-price">' . $value_price . '</div>
                                <div class="item-count">
                                    <div class="number">' . $value["count"] . '</div>
                                    <div class="counter">
                                        <div class="counter-m"><span></span></div>
                                        <div class="counter-n">' . $value["count"] . '</div>
                                        <div class="counter-p"><span></span><span></span></div>
                                    </div>
                                </div>
                            </div>
                            <div class="item-specifications" data-sku_id=\'' . (json_encode($value["sku_id"], JSON_UNESCAPED_UNICODE)) . '\'>
                                ' . (isset($value["sku"]) ? parseSku($value["sku"]) : "") . '
                            </div>
                        </div>
                        <div class="item-delete">
                            <div class="delete-div">删除</div>
                        </div>
                    </div>
                ';
            }
            $sign = 1;
        }
    }
    if ($sign == 1) {
        echo '</div>';
    }
}

//处理套装
function shoppingcartTz($cart_arr)
{
    global $url, $path;
    foreach ($cart_arr as $cart_index => $cart_content) {
        if ($cart_content["info"]["cart_type"] == 1) {
            echo '
                <div class="tz-container container" data-id="' . $cart_content["info"]["id"] . '" data-cartid="' . $cart_content["info"]["cart_id"] . '" data-cart_type="1" data-discount="' . $cart_content["info"]["discount"] . '" >
                    <div class="header-info">
                        <div class="header-check">
                            <div class="svg-border tz-check-i" data-checked="true"><img class="svg-checkbox" src="images/check-icon.png"><input type="checkbox" checked></div>
                        </div>
                        <div class="item-image">
                            <img src="' . $url . $path . $cart_content["info"]["img_url"] . '">
                        </div>
                        <div class="header-content">
                            <div class="header-title">' . $cart_content["info"]["name"] . '</div>
                            <div class="tz-number">
                                <div class="tz-tag">套装套数:</div>
                                <div class="number">' . $cart_content["info"]["count"] . '</div>
                                <div class="counter">
                                    <div class="counter-m"><span></span></div>
                                    <div class="counter-n">' . $cart_content["info"]["count"] . '</div>
                                    <div class="counter-p"><span></span><span></span></div>
                                </div>
                            </div>
                            <div class="tz-edit">
                                <div class="edit edit-count">编辑数量</div>
                                <div class="d"><div class="dd"></div></div>
                                <div class="edit edit-delete">删除套装</div>
                            </div>
                        </div>
                    </div>';
            foreach ($cart_content["items"] as $item_index => $value) {
                intval($value["price_base"]) ? $value_price = $value["price_base"] + $value["_price_custom"] : $value_price = "请询价";
                isset($cart_content["info"]["exclude"]) && in_array($value["item_id"], $cart_content["info"]["exclude"]) ? $isExclude = true : $isExclude = false;
                echo '
                <div class="item-div ' . ($isExclude ? "exclude" : "") . '" data-itemid="' . $value["item_id"] . '" data-priceid="' . $value["price_id"] . '">
                    <div class="item-check">
                    </div>
                    <div class="item-image">
                        <img src="' . $url . $path . $value["img_url"] . '">
                    </div>
                    <div class="item-info">
                        <div class="item-title">' . $value["name"] . '</div>
                        <div class="item-specifications" data-sku_id=\'' . (json_encode($value["sku_id"], JSON_UNESCAPED_UNICODE)) . '\'>
                            ' . (isset($value["sku"]) ? parseSku($value["sku"]) : "") . '
                        </div>
                        <div class="item-number">
                            ' . ($isExclude ? "<div style='display:table;'><del style='color:#999;line-height:5px;display:table-cell;'><div class='item-price' style='color:#999;'>" . $value_price . "</div></del><span style='display:table-cell;'>&nbsp;赠品</span></div>" : "<div class='item-price'>" . $value_price . "</div>") . '
                            <div class="item-count">
                                <div class="number">' . $value["count"] . '</div>
                            </div>
                        </div>
                    </div>
                </div>';
            }
            echo '</div>';
        }
    }
}

function checkAddress($address)
{
    global $conn;
    $sql = 'SELECT id FROM grp_city WHERE `name` = "' . $address . '"';
    $res = mysqli_query($conn, $sql);
    $res = mysqli_fetch_array($res);
    $id = intval($res['id']);

    if ($id % 10000 == 0) {
        $sql2 = 'SELECT * FROM grp_city WHERE `id` LIKE "' . intval($id / 10000) . '%"';
        $res2 = mysqli_query($conn, $sql2);
        if ($res2->num_rows > 1) {
            echo '{"result":0}';
        } else {
            echo '{"result":1}';
        }
    } elseif ($id % 100 == 0) {
        $sql2 = 'SELECT * FROM grp_city WHERE `id` LIKE "' . intval($id / 100) . '%"';
        $res2 = mysqli_query($conn, $sql2);
        if ($res2->num_rows > 1) {
            echo '{"result":0}';
        } else {
            echo '{"result":1}';
        }
    } else {
        echo '{"result":1}';
    }
}

//判断单品和套装是否有优惠券
function getItemCoupon($id_arr, $user_id, $count_arr)
{
    $id_arr[] = 0;
    global $conn, $url, $path;
    $sql = "SELECT 
				sys_item.id,
				sys_item.`name` AS item_name,
				sys_item.price_base,
				sys_item.price_custom,
				MIN(user_coupon.id) AS user_coupon_id,
				prf_coupon.id AS coupon_id,
				prf_coupon.`name`,
				prf_coupon.title,
				prf_coupon.memo,
				prf_coupon.action,
				prf_coupon.action_id,
				prf_coupon.start_time,
				prf_coupon.end_time,
				prf_coupon.coupon_rule,
				prf_coupon.coupon_price,
				prf_coupon.price,
				prf_coupon.user_types,
				prf_coupon.shipping,
				sys_image.url
			FROM `user_coupon`,sys_item,user_info,(
					SELECT 
						IF(pay_user_discount.post_sales_service IS NULL,0,pay_user_discount.post_sales_service) AS service,
						IF(pay_user_discount.sales_type IS NULL,1,pay_user_discount.sales_type) AS sales_type
					FROM user_info LEFT JOIN pay_user_discount ON user_info.user_type = pay_user_discount.user_type AND user_info.user_type_class = pay_user_discount.user_type_class
					WHERE user_info.id = " . $user_id . "
				) user_discount, prf_coupon
			LEFT JOIN sys_image ON prf_coupon.img_id = sys_image.id
			WHERE user_coupon.uid = " . $user_id . "
			AND user_coupon.useing_time = 0
			AND user_info.id = `user_coupon`.uid
			AND user_discount.sales_type = 1
			AND (sys_item.id = prf_coupon.action_id OR prf_coupon.action_id = 0)
			AND sys_item.id IN(" . implode(',', $id_arr) . ")
			AND user_coupon.coupon_id = prf_coupon.id
			AND (
				  (prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time = 0)
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time = 0)
			)
			AND user_coupon.state = 0
			AND prf_coupon.action = 'item'
			AND prf_coupon.action_id IN (" . implode(',', $id_arr) . ")
			AND prf_coupon.state = 1
			GROUP BY prf_coupon.id;";
    //AND (NOT (prf_coupon.shipping = 0 AND user_discount.service = 0))
    $res = mysqli_query($conn, $sql);
    $arr = [];
    while ($row = mysqli_fetch_array($res)) {
        if ($row['coupon_rule'] == 'M' && $count_arr[$row['id']] * ($row['price_custom'] + $row['price_base']) < $row['coupon_price']) {
            continue;
        } elseif ($row['coupon_rule'] == 'N' && $count_arr[$row['id']] * ($row['price_custom'] + $row['price_base']) / $row['coupon_price'] < 1) {
            continue;
        }
        $arr[$row['user_coupon_id']] = [
            'id' => $row['user_coupon_id'],
            'coupon_id' => $row['coupon_id'],
            'name' => $row['name'],
            'title' => $row['title'],
            'memo' => $row['memo'],
            'action' => $row['action'],
            'action_id' => $row['action_id'],
            'action_name' => $row['item_name'],
            'start_time' => $row['start_time'],
            'end_time' => $row['end_time'],
            'coupon_rule' => $row['coupon_rule'],
            'coupon_price' => $row['coupon_price'],
            'price' => $row['price'],
            'user_type' => $row['user_types'],
            'shipping' => $row['shipping'],
            'url' => $url . $path . $row['url'],
        ];
    }
    return $arr;
}

function getTzCoupon($id_arr, $user_id, $count_arr)
{
    $id_arr[] = 0;
    global $conn, $url, $path;
    $sql = "SELECT 
				taozhuang.sid AS id,
				taozhuang.`name` AS item_name,
				MIN(user_coupon.id) AS user_coupon_id,
				prf_coupon.id AS coupon_id,
				prf_coupon.`name`,
				prf_coupon.title,
				prf_coupon.memo,
				prf_coupon.action,
				prf_coupon.action_id,
				prf_coupon.start_time,
				prf_coupon.end_time,
				prf_coupon.coupon_rule,
				prf_coupon.coupon_price,
				prf_coupon.price,
				prf_coupon.user_types,
				prf_coupon.shipping,
				sys_image.url
			FROM `user_coupon`,taozhuang,user_info,(
					SELECT 
						IF(pay_user_discount.post_sales_service IS NULL,0,pay_user_discount.post_sales_service) AS service,
						IF(pay_user_discount.sales_type IS NULL,2,pay_user_discount.sales_type) AS sales_type
					FROM user_info LEFT JOIN pay_user_discount ON user_info.user_type = pay_user_discount.user_type AND user_info.user_type_class = pay_user_discount.user_type_class
					WHERE user_info.id = " . $user_id . "
				) user_discount, prf_coupon 
			LEFT JOIN sys_image ON prf_coupon.img_id = sys_image.id
			WHERE user_coupon.uid = " . $user_id . "
			AND user_coupon.useing_time = 0
			AND user_info.id = `user_coupon`.uid
			AND user_discount.sales_type = 2
			AND (taozhuang.sid = prf_coupon.action_id OR prf_coupon.action_id = 0)
			AND taozhuang.sid IN(" . implode(',', $id_arr) . ")
			AND user_coupon.coupon_id = prf_coupon.id
			AND (
				  (prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time = 0)
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time = 0)
			)
			AND user_coupon.state = 0
			AND prf_coupon.action = 'set'
			AND prf_coupon.action_id IN (" . implode(',', $id_arr) . ")
			AND prf_coupon.state = 1
			GROUP BY prf_coupon.id;";
    //AND (NOT (prf_coupon.shipping = 0 AND user_discount.service = 0))
    $res = mysqli_query($conn, $sql);
    $arr = [];
    while ($row = mysqli_fetch_array($res)) {
        $tz_price = tzPrice($row['id']);
        if ($row['coupon_rule'] == 'M' && $tz_price * $count_arr[$row['id']] < $row['coupon_price']) {
            continue;
        } elseif ($row['coupon_rule'] == 'N' && $tz_price * $count_arr[$row['id']] / $row['coupon_price'] < 1) {
            continue;
        }
        $arr[$row['user_coupon_id']] = [
            'id' => $row['user_coupon_id'],
            'coupon_id' => $row['coupon_id'],
            'name' => $row['name'],
            'title' => $row['title'],
            'memo' => $row['memo'],
            'action' => $row['action'],
            'action_id' => $row['action_id'],
            'action_name' => $row['action_id'] == 0 ? '套装通用' : $row['item_name'],
            'start_time' => $row['start_time'],
            'end_time' => $row['end_time'],
            'coupon_rule' => $row['coupon_rule'],
            'coupon_price' => $row['coupon_price'],
            'price' => $row['price'],
            'user_type' => $row['user_types'],
            'shipping' => $row['shipping'],
            'url' => $url . $path . $row['url'],
        ];
    }
    return $arr;
}

function tzPrice($tzid)
{
    global $conn;
    $sql = "SELECT SUM(sys_item.price_base+sys_item.price_custom) AS sum_price
			FROM `taozhuang_pos` LEFT JOIN sys_item ON taozhuang_pos.item_id = sys_item.id WHERE taozhuang_pos.tzid=" . $tzid . " AND taozhuang_pos.pay_state=1;";
    $res = mysqli_query($conn, $sql);
    $row = mysqli_fetch_array($res);
    return $row[0];
}

//查找品牌优惠券
function getBrandCoupon($item_id_arr, $user_id, $count_arr)
{
    $item_id_arr[] = 0;
    global $conn, $url, $path;
    $sql = "SELECT DISTINCT
			MIN(user_coupon.id) AS user_coupon_id,
			prf_coupon.id AS coupon_id,
			prf_coupon.`name`,
			prf_coupon.title,
			prf_coupon.memo,
			prf_coupon.action,
			prf_coupon.action_id,
			grp_brand.`name` AS action_name,
			prf_coupon.start_time,
			prf_coupon.end_time,
			prf_coupon.coupon_rule,
			prf_coupon.coupon_price,
			prf_coupon.price,
			prf_coupon.user_types,
			prf_coupon.shipping,
			sys_image.url
		FROM sys_item,user_coupon,grp_brand,user_info,(
					SELECT 
						IF(pay_user_discount.post_sales_service IS NULL,0,pay_user_discount.post_sales_service) AS service,
						IF(pay_user_discount.sales_type IS NULL,1,pay_user_discount.sales_type) AS sales_type
					FROM user_info LEFT JOIN pay_user_discount ON user_info.user_type = pay_user_discount.user_type AND user_info.user_type_class = pay_user_discount.user_type_class
					WHERE user_info.id = " . $user_id . "
				) user_discount,prf_coupon
		LEFT JOIN sys_image ON prf_coupon.img_id = sys_image.id
		WHERE prf_coupon.action = 'brand'
		AND user_coupon.useing_time = 0
		AND user_info.id = `user_coupon`.uid
		AND user_discount.sales_type = 1
		AND grp_brand.id = prf_coupon.action_id
		AND user_coupon.uid = " . $user_id . "
		AND user_coupon.coupon_id = prf_coupon.id
		AND sys_item.brand_id = prf_coupon.action_id
		AND prf_coupon.state = 1
		AND (
				  (prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time = 0)
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time = 0)
			)
		AND sys_item.id IN(" . implode(',', $item_id_arr) . ")
		GROUP BY prf_coupon.id;";
    //AND (NOT (prf_coupon.shipping = 0 AND user_discount.service = 0))
    $res = mysqli_query($conn, $sql);
    $coupon = [];
    while ($row = mysqli_fetch_array($res)) {
        $coupon[$row['user_coupon_id']] = [
            'id' => $row['user_coupon_id'],
            'coupon_id' => $row['coupon_id'],
            'name' => $row['name'],
            'title' => $row['title'],
            'memo' => $row['memo'],
            'action' => $row['action'],
            'action_id' => $row['action_id'],
            'action_name' => $row['action_name'],
            'start_time' => $row['start_time'],
            'end_time' => $row['end_time'],
            'coupon_rule' => $row['coupon_rule'],
            'coupon_price' => $row['coupon_price'],
            'price' => $row['price'],
            'user_type' => $row['user_types'],
            'shipping' => $row['shipping'],
            'url' => $url . $path . $row['url'],
        ];
    }
    $sql2 = "SELECT id,price_custom,price_base,brand_id FROM sys_item WHERE id IN(" . implode(',', $item_id_arr) . ")";
    $res2 = mysqli_query($conn, $sql2);
    $item_arr = [];
    while ($row = mysqli_fetch_array($res2)) {
        $item_arr[] = $row;
    }
    foreach ($coupon as $key => $value) {
        $price = 0;
        foreach ($item_arr as $i => $item) {
            if ($item['brand_id'] == $value['action_id']) {
                $price = $price + ($item['price_base'] + $item['price_custom']) * $count_arr[$item['id']];
            }
        }
        if ($price == 0 || $value['coupon_rule'] == 'M' && $price < $value['coupon_price']) {
            unset($coupon[$key]);
        }
        if ($price == 0 || $value['coupon_rule'] == 'N' && $price < $value['coupon_price']) {
            unset($coupon[$key]);
        }
    }
    return $coupon;
}

//查找类目优惠券
function getClassCoupon($item_id_arr, $user_id, $count_arr)
{
    if (empty($item_id_arr)) {
        return [];
    }
    $item_id_arr[] = 0;
    global $conn, $url, $path;
    $sql = "SELECT DISTINCT
			MIN(user_coupon.id) AS user_coupon_id,
			prf_coupon.id AS coupon_id,
			prf_coupon.`name`,
			prf_coupon.title,
			prf_coupon.memo,
			prf_coupon.action,
			prf_coupon.action_id,
			grp_class.`name` AS action_name,
			prf_coupon.start_time,
			prf_coupon.end_time,
			prf_coupon.coupon_rule,
			prf_coupon.coupon_price,
			prf_coupon.price,
			prf_coupon.user_types,
			prf_coupon.shipping,
			sys_image.url
		FROM sys_item,user_coupon,grp_class,user_info,(
					SELECT 
						IF(pay_user_discount.post_sales_service IS NULL,0,pay_user_discount.post_sales_service) AS service,
						IF(pay_user_discount.sales_type IS NULL,1,pay_user_discount.sales_type) AS sales_type
					FROM user_info LEFT JOIN pay_user_discount ON user_info.user_type = pay_user_discount.user_type AND user_info.user_type_class = pay_user_discount.user_type_class
					WHERE user_info.id = " . $user_id . "
				) user_discount,prf_coupon
		LEFT JOIN sys_image ON prf_coupon.img_id = sys_image.id
		WHERE prf_coupon.action = 'class'
		AND user_coupon.useing_time = 0
		AND user_discount.sales_type = 1
		AND grp_class.id = prf_coupon.action_id
		AND user_coupon.uid = " . $user_id . "
		AND user_coupon.coupon_id = prf_coupon.id
		AND sys_item.class_id = prf_coupon.action_id
		AND prf_coupon.state = 1
		AND (
				  (prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time = 0)
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time = 0)
			)
		AND sys_item.id IN(" . implode(',', $item_id_arr) . ")
		GROUP BY prf_coupon.id;";
    //AND (NOT (prf_coupon.shipping = 0 AND user_discount.service = 0))
    $res = mysqli_query($conn, $sql);
    $coupon = [];
    while ($row = mysqli_fetch_array($res)) {
        $coupon[$row['user_coupon_id']] = [
            'id' => $row['user_coupon_id'],
            'coupon_id' => $row['coupon_id'],
            'name' => $row['name'],
            'title' => $row['title'],
            'memo' => $row['memo'],
            'action' => $row['action'],
            'action_id' => $row['action_id'],
            'action_name' => $row['action_name'],
            'start_time' => $row['start_time'],
            'end_time' => $row['end_time'],
            'coupon_rule' => $row['coupon_rule'],
            'coupon_price' => $row['coupon_price'],
            'price' => $row['price'],
            'user_type' => $row['user_types'],
            'shipping' => $row['shipping'],
            'url' => $url . $path . $row['url'],
        ];
    }
    $sql2 = "SELECT id,price_custom,price_base,class_id FROM sys_item WHERE id IN(" . implode(',', $item_id_arr) . ")";
    $res2 = mysqli_query($conn, $sql2);
    $item_arr = [];
    while ($row = mysqli_fetch_array($res2)) {
        $item_arr[] = $row;
    }
    foreach ($coupon as $key => $value) {
        $price = 0;
        foreach ($item_arr as $i => $item) {
            if ($item['class_id'] == $value['action_id']) {
                $price = $price + ($item['price_base'] + $item['price_custom']) * $count_arr[$item['id']];
            }
        }
        if ($price == 0 || $value['coupon_rule'] == 'M' && $price < $value['coupon_price']) {
            unset($coupon[$key]);
        }
        if ($price == 0 || $value['coupon_rule'] == 'N' && $price < $value['coupon_price']) {
            unset($coupon[$key]);
        }
    }
    return $coupon;
}

function getAllCoupon($user_id)
{
    global $conn, $url, $path;
    $sql = "SELECT 
				MIN(user_coupon.id) AS user_coupon_id,
				prf_coupon.id AS coupon_id,
				prf_coupon.`name`,
				prf_coupon.title,
				prf_coupon.memo,
				prf_coupon.action,
				prf_coupon.action_id,
				prf_coupon.start_time,
				prf_coupon.end_time,
				prf_coupon.coupon_rule,
				prf_coupon.coupon_price,
				prf_coupon.price,
				prf_coupon.user_types,
				prf_coupon.shipping,
				sys_image.url
			FROM `user_coupon`, prf_coupon
			LEFT JOIN sys_image ON prf_coupon.img_id = sys_image.id
			WHERE user_coupon.uid = " . $user_id . "
			AND user_coupon.useing_time = 0
			AND user_coupon.coupon_id = prf_coupon.id
			AND (
				  (prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time = 0)
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time = 0)
			)
			AND user_coupon.state = 0
			AND prf_coupon.action = 'all'
			AND prf_coupon.state = 1
			GROUP BY prf_coupon.id;";
    $res = mysqli_query($conn, $sql);
    $arr = [];
    while ($row = mysqli_fetch_array($res)) {
        $arr[$row['user_coupon_id']] = [
            'id' => $row['user_coupon_id'],
            'coupon_id' => $row['coupon_id'],
            'name' => $row['name'],
            'title' => $row['title'],
            'memo' => $row['memo'],
            'action' => $row['action'],
            'action_id' => $row['action_id'],
            'action_name' => '全场',
            'start_time' => $row['start_time'],
            'end_time' => $row['end_time'],
            'coupon_rule' => $row['coupon_rule'],
            'coupon_price' => $row['coupon_price'],
            'price' => $row['price'],
            'user_type' => $row['user_types'],
            'shipping' => $row['shipping'],
            'url' => $url . $path . $row['url'],
        ];
    }
    return $arr;
}